import { clearRedundancyKey, formatDate, throttle } from '../../../../../../utils/jk/jk-tool';
import checkboxPopover from '../../../../order/components/form-box/checkbox-popover';
import remoteSearchOrderInput from '../remote-search-order-input';
import { validateArr } from '../../../../../../utils/jk/validator';
import {
	qslProductionClearRelease,
	qslProductionCreate,
	qslProductionGet,
	qslProductionRelease,
	qslProductionUpdate
} from '../../../../../../api/production/qslb';
import processInfoItem from '../process-info-item';
import { spinProcessPage } from '../../../../../../api/technology/process';
import { productionPrdOrderGet } from '../../../../../../api/production/order';
import getTubeColor from './get-tube-color';
import remoteSearchPrdCottonInput from '../remote-search-prd-cotton-input';
import { foreSpinPlanStateList, openStateList } from '../../../../../../utils/jk/status-option-list';
import handlerCache from '../../../../../../mixins/handler-cache';
import { ppfProductionLineGet, ppfProductionLinePage } from '../../../../../../api/production/produtionLine';
import remoteSearchProductInput from '../../../../order/components/remote-search-product-input';
import remoteSearchBatchCodeInput from '../../../../qhPrd/productConfigCotton/components/remote-search-batch-code-input';
import noticePopoverBar from '../notice-popover-bar';
export default {
	components: {
		noticePopoverBar,
		remoteSearchBatchCodeInput,
		remoteSearchProductInput,
		remoteSearchPrdCottonInput,
		processInfoItem,
		remoteSearchOrderInput,
		checkboxPopover
	},
	mixins: [getTubeColor, handlerCache],
	props: {
		createMethod: {
			type: String,
			default: 'page' // 页面page或者弹窗dialog
		},
		pageType: {
			type: String,
			default: ''
		},
		orderId: { // 订单ID,订单分配创建时传入
			type: [String, Number],
			default: ''
		},
		frontPlanId: { // 前纺计划ID, 编辑、详情时传入
			type: [String, Number],
			default: ''
		},
		height: {
			type: Number,
			default: null
		}
	},
	data() {
		return {
			apiItem: {
				'save': qslProductionCreate,
				'update': qslProductionUpdate,
				'get': qslProductionGet
			},
			dataId: null,
			orderDataId: null,
			foreSpinPlanStateList: foreSpinPlanStateList,
			processList: [],
			tableData: [],
			unReleaseBtnLoading: false,
			releaseBtnLoading: false,
			saveBtnLoading: false,
			workshopList: [],
			saveDialogState: false,
			materialList: [],
			showLoading: false,
			openStateList: openStateList,
			productionLineList: [],
			ruleForm: {
				'code': '',
				'workshopId': null,
				'feedstockQty': null,
				'belongDate': '',
				'batchId': null,
				'batchCode': '',
				'productId': null,
				'productCode': '',
				'productName': '',
				'productModels': '',
				'ppfProductionLineId': null,
				'ppfProductionLineCode': null,
				'ppfProductionLineName': null,
				'productionQty': 0,
				'serviceState': 0,
				'workshopCode': '',
				'workshopName': '',
				'productOrderPlanId': null,
				'productOrderPlanCode': '',
				'ppfCottonBlendingId': null,
				'ppfCottonBlendingCode': '',
				'remark': '',
				'processPlanLineList': []
			},
			rules: {
				productOrderId: [{ required: true, trigger: 'change' }],
				cardSliverColors: [{ required: true, validator: validateArr, trigger: 'change' }],
				halfLifeStripColors: [{ required: true, validator: validateArr, trigger: 'change' }],
				drawnSliverColors: [{ required: true, validator: validateArr, trigger: 'change' }],
				belongDate: [{ required: true, trigger: 'change' }],
				drawnSliverBatchId: [{ required: true, trigger: 'change' }],
				productionQty: [{ required: true, trigger: 'change' }],
				productId: [{ required: true, trigger: 'change' }],
				workshopId: [{ required: true, trigger: 'change' }],
				batchId: [{ required: true, trigger: 'change' }]
			},
			defaultProcessList: [],
			technologyOrderInfo: {
				'batchCode': '',
				'code': '',
				'dailyYield': null,
				'efficiencyPercent': null,
				'fixedLength': null,
				'gramWeight': null,
				'id': null,
				'machineModelCode': '',
				'machineModelId': null,
				'machineModelName': '',
				'meters': null,
				'moistureRegain': null,
				'numbers': null,
				'processCode': '',
				'processId': null,
				'processName': '',
				'productCode': '',
				'productId': null,
				'productModels': '',
				'productName': '',
				'specDate': '',
				'specEmpId': null,
				'specEmpName': '',
				'specSheetParamList': [],
				'spindleNum': 0
			},
			editMachineTechnologyInfo: {},
			machineIdx: null,
			batchList: []
		};
	},
	methods: {
		onSelectProductChange(e) {
			if (e && Object.keys(e).length) {
				this.$set(this.ruleForm, 'productOrderBatchList', []);
				this.$set(this.ruleForm, 'batchId', null);
				this.$set(this.ruleForm, 'batchCode', '');
				this.$set(this.ruleForm, 'productId', e.id);
				this.$set(this.ruleForm, 'productCode', e.code);
				this.$set(this.ruleForm, 'productName', e.name);
				this.$set(this.ruleForm, 'productModels', e.models);
				this.$set(this.ruleForm, 'unitId', e.unitId);
				this.$set(this.ruleForm, 'unitCode', e.unitCode);
				this.$set(this.ruleForm, 'unitName', e.unitName);
				this.setChildTableInfo();
			}
		},
		setChildTableInfo() {
			this.ruleForm.processPlanLineList.forEach(x => {
				this.$set(x, 'productId', this.ruleForm.productId);
				this.$set(x, 'productCode', this.ruleForm.productCode);
				this.$set(x, 'productName', this.ruleForm.productName);
				this.$set(x, 'productModels', this.ruleForm.productModels);
				this.$set(x, 'unitId', this.ruleForm.unitId);
				this.$set(x, 'unitCode', this.ruleForm.unitCode);
				this.$set(x, 'unitName', this.ruleForm.unitName);

				this.$set(x, 'batchId', this.ruleForm.batchId);
				this.$set(x, 'batchCode', this.ruleForm.batchCode);
			});
		},
		onProductionQtyChange(e) {
			this.ruleForm.processPlanLineList.forEach(x => {
				x.mbInfo.productionQty = e;
			});
		},
		onSelectPrdCottonChange(e) {
			if (Object.keys(e).length) {
				this.$set(this.ruleForm, 'ppfCottonBlendingId', e.id);
				this.$set(this.ruleForm, 'ppfCottonBlendingCode', e.code);
			}
		},
		onSelectOrderChange(resData) {
			if (resData && Object.keys(resData).length) {
				this.getOrderDetailRequest(resData.id);
			}
		},
		onSelectBatchCodeChange(e) {
			if (Object.keys(e).length) {
				this.$set(this.ruleForm, 'batchId', e.id);
				this.$set(this.ruleForm, 'batchCode', e.batchCode);
				this.ruleForm.processPlanLineList.forEach(x => {
					this.$set(x, 'batchId', e.id);
					this.$set(x, 'batchCode', e.batchCode);
				});
			}
		},
		onUnReleaseBtn: throttle((e, _this) => {
			_this.unReleaseBtnLoading = true;
			qslProductionClearRelease({ id: _this.ruleForm.id }).then(res => {
				_this.unReleaseBtnLoading = false;
				if (res.data.status === 200) {
					_this.getDependentData();
				}
			});
		}),
		onReleaseBtn: throttle((e, _this) => {
			_this.releaseBtnLoading = true;
			qslProductionRelease({ id: _this.ruleForm.id }).then(res => {
				_this.releaseBtnLoading = false;
				if (res.data.status === 200) {
					_this.getDependentData();
				}
			});
		}),
		setDependentDataOfForm() {
			let params = JSON.parse(JSON.stringify(this.ruleForm));
			const ppfProductionLineItem = this.productionLineList.find(x => x.id === params.ppfProductionLineId) || {};
			params.ppfProductionLineCode = ppfProductionLineItem.code;
			params.ppfProductionLineName = ppfProductionLineItem.name;

			const workshopItem = this.workshopList.find(x => x.id === params.workshopId) || {};
			params.workshopCode = workshopItem.code;
			params.workshopName = workshopItem.name;
			params.processPlanLineList.forEach(x => {
				delete x.showInputColor;
				delete x.showOutColor;
				delete x.inputColorList;
				delete x.outColorList;
			});
			delete params.productOrder;
			params = clearRedundancyKey(params, ['productOrderBatch']);
			return params;
		},
		onConfirmBtn() {
			this.$refs['ruleForm'].validate(valid => {
				if (valid) {
					this.createAndUpdateRequest();
				} else {
					this.$emit('on-res', false);
					this.$tipsBar(this, 'validator');
				}
			});
		},
		createAndUpdateRequest() {
			this.saveBtnLoading = true;
			// 新增
			if (!this.dataId) {
				this.ruleForm.id = null;
				this.apiItem.save(this.setDependentDataOfForm()).then(res => {
					this.saveBtnLoading = false;
					if (res.data.status === 200) {
						this.dataId = res.data.res;
						this.$tipsBar(this, 'save');
						if (this.createMethod === 'dialog') {
							this.$emit('on-res', true);
						} else {
							this.onJump(this.dataId);
						}
					} else {
						if (this.createMethod === 'dialog') {
							this.$emit('on-res', false);
						}
					}
				});
				return;
			}
			// 编辑
			this.apiItem.update(this.setDependentDataOfForm()).then(res => {
				this.saveBtnLoading = false;
				if (res.data.status === 200) {
					this.$tipsBar(this, 'save');
					if (this.createMethod === 'dialog') {
						this.$emit('on-res', true);
					} else {
						this.getDependentData();
					}
				} else {
					if (this.createMethod === 'dialog') {
						this.$emit('on-res', false);
					}
				}
			});
		},
		setProcessColorInfo(data) {
			let arr = data && data.length ? JSON.parse(JSON.stringify(data)) : [];
			const processConf = {
				SM: {
					showInputColor: false,
					showOutColor: true,
					showStartTime: false,
					inputColorList: [],
					outColorList: JSON.parse(JSON.stringify(this.smColorList))
				},
				BT: {
					showInputColor: true,
					showOutColor: true,
					showStartTime: true,
					inputColorList: JSON.parse(JSON.stringify(this.smColorList)),
					outColorList: JSON.parse(JSON.stringify(this.btColorList))
				},
				TB: {
					showInputColor: true,
					showOutColor: true,
					showStartTime: true,
					inputColorList: JSON.parse(JSON.stringify(this.smColorList)),
					outColorList: JSON.parse(JSON.stringify(this.btColorList))
				},
				MB: {
					showInputColor: true,
					showOutColor: true,
					showStartTime: true,
					inputColorList: JSON.parse(JSON.stringify(this.btColorList)),
					outColorList: JSON.parse(JSON.stringify(this.btColorList))
				},
				CS: {
					showInputColor: true,
					showOutColor: true,
					showStartTime: true,
					inputColorList: JSON.parse(JSON.stringify(this.btColorList)),
					outColorList: JSON.parse(JSON.stringify(this.csColorList))
				},
				XS: {
					showInputColor: true,
					showOutColor: true,
					showStartTime: true,
					inputColorList: JSON.parse(JSON.stringify(this.csColorList)),
					outColorList: JSON.parse(JSON.stringify(this.xsColorList))
				}
			};
			arr = arr ? arr.map(x => {
				if (processConf[x.processCode]) {
					x = {
						...x,
						...processConf[x.processCode]
					};
				}
				return x;
			}) : [];
			return arr;
		},
		getDetailRequest() {
			return this.apiItem.get({ id: this.dataId }).then(res => {
				if (res.data.status === 200) {
					const resData = JSON.parse(JSON.stringify(res.data.res));
					resData.processPlanLineList = this.setProcessColorInfo(resData.processPlanLineList);

					let machineData = [];
					// 通过前纺排产中心选择机台时，将机台(过滤掉已有的且未了机的机台)放入对应的工序内
					if (this.$route.query.machineList) {
						machineData = JSON.parse(this.$route.query.machineList);
					}
					const allExistMachineList = [];
					resData.processPlanLineList.forEach(processItem => {
						processItem.machineList.forEach(machineItem => {
							allExistMachineList.push(machineItem);
						});
					});
					// 过滤已有的且未了机的机台
					machineData.forEach(newMachineItem => {
						newMachineItem.isExit = false;
						allExistMachineList.forEach(exitMachineItem => {
							// 未了机的
							if (newMachineItem.machineId === exitMachineItem.machineId && exitMachineItem.openingState < 4) {
								newMachineItem.isExit = true;
							}
						});
					});
					machineData = machineData.filter(x => !x.isExit);
					machineData.forEach(newMachineItem => {
						resData.processPlanLineList.forEach(processItem => {
							if (newMachineItem.processId === processItem.processId) {
								processItem.machineList.push({
									machineId: newMachineItem.machineId,
									machineCode: newMachineItem.machineCode,
									machineName: newMachineItem.machineName,
									processId: newMachineItem.processId,
									processCode: newMachineItem.processCode,
									processName: newMachineItem.processName,
									inputTubeColorList: processItem.inputTubeColorList || [],
									outputTubeColorList: processItem.outputTubeColorList || [],
									specSheet: {
										gramWeight: processItem.gramWeight || 0,
										meters: processItem.meters || 0
									},
									gramWeight: processItem.gramWeight || 0,
									meters: processItem.gramWeight || 0
								});
							}
						});
					});
					this.ruleForm = resData;
					this.$nextTick(() => {
						this.$refs.noticePopoverBar.getListRequest();
					});
				}
			});
		},
		onJumpOrder() {
			this.$store.dispatch('tagsView/delView', { path: this.$route.path });
			this.$toMainRouter({
				name: 'editPrdOrder',
				query: {
					id: this.ruleForm.productOrderId
				}
			});
		},
		onPrintBtn() {
			const routeUrl = this.$router.resolve({
				name: 'printForeSpinningPlan',
				query: {
					id: this.ruleForm.id
				}
			});
			window.open(routeUrl.href, '_blank');
		},
		onJumpList() {
			this.$store.dispatch('tagsView/delView', { path: this.$route.path });
			this.$toMainRouter({
				name: 'ForeSpinningPlan'
			});
		},
		getProcessListRequest() {
			return spinProcessPage({ auditState: 1 }).then(res => {
				if (res.data.status === 200) {
					let resData = res.data.res || [];
					resData = resData.filter(x => ['SM', 'BT', 'TB', 'EB', 'MB', 'CS'].includes(x.code.toUpperCase()));
					this.processList = resData;
					this.defaultProcessList = this.processList.filter(x => ['SM', 'BT', 'CS'].includes(x.code.toUpperCase())).map(x => {
						return {
							processId: x.id,
							processCode: x.code,
							processName: x.name,
							machineList: []
						};
					});
				}
			});
		},
		onBatchChange(e) {
			const batchItem = this.batchList.find(x => x.batchId === e) || {};
			this.$set(this.ruleForm, 'batchCode', batchItem.batchCode);
		},
		setOrderInfo(resData) {
			this.$set(this.ruleForm, 'productOrderId', resData.productOrderId);
			this.$set(this.ruleForm, 'productOrderCode', resData.productOrderCode);
			this.$set(this.ruleForm, 'batchId', resData.batchId);
			this.$set(this.ruleForm, 'batchCode', resData.batchCode);

			// 品种信息
			this.$set(this.ruleForm, 'productId', resData.productId);
			this.$set(this.ruleForm, 'productCode', resData.productCode);
			this.$set(this.ruleForm, 'productName', resData.productName);
			this.$set(this.ruleForm, 'productModels', resData.productModels);
			this.setChildTableInfo();
			this.$refs.ruleForm.clearValidate();
		},
		getOrderDetailRequest(id) {
			return productionPrdOrderGet({ id }).then(res => {
				if (res.data.status === 200) {
					const resData = res.data.res || {};
					// 默认取第一个批号
					const batchItem = resData.productOrderBatchList && resData.productOrderBatchList.length ? resData.productOrderBatchList[0] : {};
					const item = {
						productOrderId: resData.id,
						productOrderCode: resData.code,
						batchId: batchItem.batchId,
						batchCode: batchItem.batchCode,
						productId: resData.productId,
						productCode: resData.productCode,
						productName: resData.productName,
						productModels: resData.productModels
					};
					this.batchList = resData.productOrderBatchList;
					this.setOrderInfo(item);
				}
			});
		},
		onJump(id) {
			this.$store.dispatch('tagsView/delView', { path: this.$route.path });
			this.$toMainRouter({
				name: 'editForeSpinningPlan',
				query: { id }
			});
		},
		onLineChange(e) {
			if (e) {
				ppfProductionLineGet({ id: e }).then(res => {
					if (res.data.status === 200) {
						this.defaultProcessList = res.data.res.processList && res.data.res.processList ? res.data.res.processList.map(x => {
							if (x.machineList && x.machineList.length) {
								x.machineList.forEach(k => {
									delete k.id;
									k.specSheet = {
										gramWeight: 0,
										meters: 0
									};
									k.gramWeight = 0;
									k.meters = 0;
									k.gramWeight = 0;
									k.meters = 0;
								});
							}
							return x;
						}) : [];

						this.ruleForm.processPlanLineList.forEach(x => {
							this.defaultProcessList.forEach(k => {
								if (x.processCode === k.processCode) {
									this.$set(x, 'machineList', JSON.parse(JSON.stringify(k.machineList)));
								}
							});
						});
					}
				});
			} else {
				this.ruleForm.processPlanLineList.forEach(x => {
					this.$set(x, 'machineList', []);
				});
			}
		},
		getLineListRequest() {
			return ppfProductionLinePage({ auditState: 1 }).then(res => {
				if (res.data.status === 200) {
					this.productionLineList = res.data.res;
				}
			});
		},
		async getDependentData() {
			// 因参数的传递方式不同，为了方便使用统一存到本地变量中
			if (this.createMethod === 'page') {
				this.dataId = this.$route.query.id ? Number(this.$route.query.id) : null;
				this.orderDataId = this.$route.query.orderId ? Number(this.$route.query.orderId) : null;
			} else {
				this.dataId = this.frontPlanId;
				this.orderDataId = this.orderId;
			}
			this.showLoading = true;
			this.workshopList = this.$store.state.user.userWorkshop.workshopList;
			await this.getProcessListRequest();
			await this.getLineListRequest();
			if (this.orderDataId) await this.getOrderDetailRequest(this.orderDataId);
			await this.getSmColorListRequest();
			await this.getBtColorListRequest();
			await this.getCsColorListRequest();
			await this.getXsColorListRequest();
			if (!this.dataId) {
				const arr = this.setProcessColorInfo(JSON.parse(JSON.stringify(this.defaultProcessList)));
				// 通过前纺排产中心选择机台时，将机台放入对应的工序内
				if (this.$route.query.machineList) {
					const machineData = JSON.parse(this.$route.query.machineList);
					arr.forEach(x => {
						x.machineList = machineData.filter(k => {
							k.specSheet = {};
							return k.processCode === x.processCode;
						});
					});
				}
				this.$set(this.ruleForm, 'processPlanLineList', arr);
				this.$set(this.ruleForm, 'workshopId', this.$route.query.workshopId ? Number(this.$route.query.workshopId) : this.$store.state.user.userWorkshop.defaultWorkshopId);
				this.$set(this.ruleForm, 'workshopCode', this.$store.state.user.userWorkshop.defaultWorkshopCode);
				this.$set(this.ruleForm, 'workshopName', this.$store.state.user.userWorkshop.defaultWorkshopName);
				this.$set(this.ruleForm, 'belongDate', formatDate(Date.now()));
			}
			if (this.dataId) await this.getDetailRequest();
			this.showLoading = false;
			this.$nextTick(() => {
				this.$refs.ruleForm.clearValidate();
			});
		},
		clearCacheMethod() {
			Object.assign(this.$data, this.$options.data());
			this.$nextTick(() => {
				this.$refs.ruleForm.clearValidate();
				this.getDependentData().then();
			});
		}
	},
	mounted() {
		this.getDependentData().then();
	}
};
